<?php

	//no calling this file by itself
	if (eregi("cmsAuthenticate.php", $_SERVER['PHP_SELF'])) {
		redirectCleanly("/");
	}

	$regglobs = ini_get('register_globals');	
	if ($regglobs){
		die ("TURN OFF REGISTER GLOBALS DIMWIT!!!!");
	}
	
	require_once("cmsBasePaths.php");
	
	//now we need to fangle the include paths.. 
	// $_SERVER['HTTP_HOST'] = "www." . $_SERVER['HTTP_HOST'];
	if (strpos($_SERVER['HTTP_HOST'],"www.") !== false) {
		$base_host = substr($_SERVER['HTTP_HOST'],4);
		
	} else {
		$base_host = $_SERVER['HTTP_HOST'];
	}
	
	$_SERVER['HTTP_HOST'] = $base_host;

	$siteConfigPath = CMS_CORE_SITEBASE . $_SERVER['HTTP_HOST'] . "/htdocs/site/config";
	

	ini_set('include_path', ini_get('include_path'). ":" .$siteConfigPath );
	
	//standard includes
	require_once("cmsConfig.php");
		
	session_start();
	
	
	$error = 0;

	$authInfo = extractObjectWithKeyFromArray('authInfo', $_SESSION);
	$rememberme = extractStringWithKeyFromArray('rememberme', $_REQUEST);
	
	if (!is_null($authInfo)) {	
//		//quick pre auth test here.. check that the sessions ip has not changed.
		if (!key_exists('sessionip',$authInfo) || $authInfo->sessionip != $_SERVER['REMOTE_ADDR']){
			$authInfo = null;
			session_destroy();
			session_start();

		}
	}

		//fangle the cookie monster
	$cookieMonster = array();
	$cookieAuth = extractStringWithKeyFromArray('cmsac',$_COOKIE, null);
	if (!is_null($cookieAuth) && strlen($cookieAuth) > 3){
		$cookieCrumble = explode(':',base64_decode($cookieAuth));
		if (count($cookieCrumble)==2 ) {
			$cookieMonster['username'] = $cookieCrumble[0];
			$cookieMonster['password'] = $cookieCrumble[1];
		}
	}
		
	
	//no auth info in the session or from a cookie.. so we need to authenticate
	if (is_null($authInfo)) {

		//clobber the session..
		session_destroy();
		session_start();
						
		$authReader = new CmsTableWriter(CMS_AUTH_FORMAT,$db);
		$authOrder = array("cookieMonster","_REQUEST");		
		foreach ($authOrder as $authArrayName ) {
			
			$username = extractStringWithKeyFromArray('username', ${ $authArrayName }, null);
			$password = extractStringWithKeyFromArray('password', ${ $authArrayName }, null);
		
			if ( 
				!is_null($username) && strlen($username) > 0  && 
				!is_null($password) && strlen($password) > 0 ){		

				$authReader->resetCustomIterator(" WHERE username='$username' LIMIT 1");
				if (($res = $authReader->nextItem()) && ($res->password == md5($password))){
					//valid auth, so remember me
					$authInfo = $res;
					$authInfo->sessionip = $_SERVER['REMOTE_ADDR'];//we will use this for making sure we dont have stolen sessions..
					//session_register("authInfo");
					$db->executeQuery("SELECT gid FROM usergroup WHERE uid='".$authInfo->uid."'");
					$authInfo->gids = array();
					while ($row = $db->nextRow()) {
						$authInfo->gids[] = $row[0];
					}
					$_SESSION['authInfo'] = $authInfo;
					
					//only want to allow the cookiemonster to be set.. if been told too
					//otherwise it will be set when it comes in..
					if ($rememberme) {
						$cookieMonster['username'] = $username;
						$cookieMonster['password'] = $password;
					}
					// we can get out of the loop now
					//add the cookies here to the session
					$error =0;
					break;
				}  else {
					//there was an error
					$error = 1;
				}
			}		
		}
	}

		
	if (!is_null( $authInfo ) ) {

		//set the auth.. and refresh
		if ($rememberme==1 || (!is_null($cookieMonster) && key_exists('username',$cookieMonster) && key_exists('password',$cookieMonster))) {
			setcookie("cmsac",base64_encode($cookieMonster['username'].":".$cookieMonster['password']) ,time() + (2629744), "/cms/html/");
		}
		
		
		//get the default and refresh if its there..
		$defaultViewMode = extractNumberWithKeyFromArray('defaultViewMode', $_COOKIE, null);
		if ( !is_null($defaultViewMode)) {
			setcookie('defaultViewMode',$defaultViewMode,time() + (2629744),'/cms/html/',null,null);							
		}
		
		//get the current mode, and if its not set.. use the default..
		$currentViewMode = extractNumberWithKeyFromArray('viewMode', $_SESSION, $defaultViewMode);

		//finally, if we have tried to set the mode, we take that otherwise the current view mdoe
		$viewMode = extractNumberWithKeyFromArray('viewModeSent', $_REQUEST, $currentViewMode);
		
		//then we check the permissions to make sure that the user can access the mode..
		if( is_null($viewMode) || !permissionForMode($authInfo->uid, $viewMode, $db)) {
				//fail not allowed so set to the default of zero
				$viewMode = 0;
		}
		$_SESSION['viewMode'] = $viewMode;

		//hook up things post auth
		$cmsDocument = new CmsDocument($db, session_id());// do i actually need something this heavy here?//not sure..	

		//other post value hooks
		
	} else {
		session_destroy();// also add cookie vapouriser
		//no stale data please
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<title><?= TITLE; ?></title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<link href="/cms/css/cmslayout.css"  rel="stylesheet" type="text/css" media="screen" />
		<link href="/site/css/cmslayout.css"  rel="stylesheet" type="text/css" media="screen" />
		<script language="javascript" type="text/javascript">
		function loginmsg() {
			alert("If you tick this box then you will no longer need to log in\n" +
				"when visting Originate from this computer.\n\n" +
				"You can disable this feature at any time by logging out.\n\n" +
				"Don't use this option unless you are the only person\nwho has access to this computer.\n\n");
		}
		</script>
	</head>
	<body>
		<div id="cms_bodywrapper">
	
			<div id="cms_container">

				<div id="cms_top"><? include_once("cmsHeader.php"); ?></div>
				<div id="cms_status_home"></div>

				<div id="cms_wrapper">

					<div id="cms_intro_blurb">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td rowspan="2" valign="top"><img src="/cms/images/blurb_border.gif" alt="-" border="0" align="left" /></td>
                        <td valign="top">&nbsp;</td>
                      </tr>
                      <tr>
                        <td valign="top"><p><img src="../images/cms+intranet.gif" alt="CMS + Intranet" width="147" height="30" />
							<br />
                          <br />
							Welcome to the Originate Intranet and Content Management System. <br/>Please enter your username and password to enter.</td>
                      </tr>
                    </table>
					<p>&nbsp;</p>
					</div>

					<div id="cms_login">


					
					<img src="/cms/images/login_border.gif" alt="-" width="38" height="355" border="0" align="left" />	
					<br />


					<form name="authform" method="post" action="<?= $_SERVER['REQUEST_URI'] ?>" >
								<table width="200" border="0" cellspacing="0" cellpadding="0" align="center">
								  <tr valign="middle">
								    <td>&nbsp;</td>
								    <td><img src="/cms/images/login.gif" alt="Login" /><br />&nbsp;</td>
							      </tr>
								  <tr valign="middle"> 
									<td>Username:&nbsp; </td>
									<td> 
									  <input type="text" name="username" class="cms_authform" style="width: 145px;" value="<?= @$cookieMonster['username']?>">									</td>
								  </tr>
								  <tr valign="middle"> 
									<td>Password: &nbsp;</td>
									<td><input type="password" name="password"  class="cms_authform" style="width: 145px;" value="<?= @$cookieMonster['password']?>"/></td>
								  </tr>
								  <tr valign="middle"> 
									<td>Remember me? &nbsp;</td>
									<td><input type="checkbox" name="rememberme" onclick="javascript:if (this.checked) loginmsg();" class="cms_authform" value="1" style="width: 145px;"/></td>
								  </tr>
								  <?
									if($error) {
										?>

								  <tr>
								  	<td width="100%" colspan="2" class="cms_error">Incorrect Username or 

Password Please try again.</td>
								  </tr>

										<?
									}
								  ?>
								  <tr> 
									<td>&nbsp;</td>
									<td><div align="right">
									  
								      <a href="javascript:document.forms['authform'].submit();" class="cms_authform" ><br />
								      <img src="/cms/images/go.gif" alt="Go" /></a>
									    <input type="image" src="/cms/images/spacer.gif" />
								    </div></td>
								  </tr>
								</table>	
				  </form>
<center><img src="/cms/images/homeImage_client.jpg" alt="" /></center>		</div>					
					<div id="cms_left_sidebar"><img src="/cms/images/spacer.gif" height="100" width="1" /></div>  
				</div>
				<div id="cms_footer_home"><? include_once(CMS_BOTTOM_BAR); ?> </div>

			</div>
		</div>
</body>
</html>
<?
		die();//quietly.. dont need to carry on..//
	}
?>